package com.kuaimacode.kframework.util;

import com.kuaimacode.kframework.enums.DictTypeEnum;
import com.kuaimacode.kframework.mybatis.models.sys.Dict;
import com.kuaimacode.kframework.service.DictService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典提取工具对象
 * @author Administrator
 * @date 2018/8/14
 */
public class DictUtil {

    private static Cache dictCache = EhCacheUtil.getDictCache();

    /**
     * 获取字典值
     * @param label 字典标识
     */
    public static String value(String label){
        String value = "";
        Element dictEle = dictCache.get(label);
        if(dictEle != null){
            value = String.valueOf(dictEle.getObjectValue());
        }else {
            DictService dictService = SpringContextUtil.getBean(DictService.class);
            Dict dict = dictService.getName(label);
            if(dict != null){
                value = dict.getValue();
                dictCache.put(new Element(dict.getName(), dict.getValue()));
            }
       }
        return value;
    }

    /**
     * 获取键值对集合
     * @param label 字典标识
     */
    public static Map<String, String> keyValueList(String label){
        Map<String, String> value = null;
        Element dictEle = dictCache.get(label);
        if(dictEle != null){
            value = (Map<String, String>) dictEle.getObjectValue();
        }else {
            DictService dictService = SpringContextUtil.getBean(DictService.class);
//            Dict dict = dictService.getName(label);
//            if(dict != null && dict.getType().equals(DictTypeEnum.KEY_VALUE.getCode())){
                List<Dict> lists = dictService.getChildren(label);
                if(lists!=null && lists.size()>0){
                    value = new HashMap<>();
                    for (Dict osp : lists) {
                        value.put(osp.getCode(), osp.getValue());
                    }
                    dictCache.put(new Element(label, value));
                }

//            }
       }
        return value;
    }

    /**
     * 获取键值对集合
     * @param label 字典标识
     */
    public static Map<String, String> keyValueByPCodeList(String label,String pCode){
        Map<String, String> value = null;
        if(label == null || pCode == null){
            return new HashMap<>();
        }
//        Element dictEle = dictCache.get(label+pCode);
//        if(dictEle != null){
//            value = (Map<String, String>) dictEle.getObjectValue();
//        }else {
            DictService dictService = SpringContextUtil.getBean(DictService.class);
//            Dict dict = dictService.getName(label);
//            if(dict != null && dict.getType().equals(DictTypeEnum.KEY_VALUE.getCode())){
                List<Dict> lists = dictService.getChildrenByPId(label,pCode);
                value = new HashMap<>();
                for (Dict osp : lists) {
                    value.put(osp.getCode(), osp.getValue());
                }
//                dictCache.put(new Element(label+pCode, value));
//            }
//        }
        return value;
    }


    /**
     * 获取键值对集合
     * @param label 字典标识
     */
    public static List<Dict> getChildren(String label){
        List<Dict> lists = null;
        //Element dictEle = dictCache.get(label);
        //if(dictEle != null){
        //    value = (Map<String, String>) dictEle.getObjectValue();
        //}else {
        DictService dictService = SpringContextUtil.getBean(DictService.class);
        //Dict dict = dictService.getName(label);
        //if(dict != null && dict.getType().equals(DictTypeEnum.KEY_VALUE.getCode())){
            lists = dictService.getChildren(label);
            //dictCache.put(new Element(dict.getName(), value));
       // }
        // }
        return lists;
    }

    /**
     * 获取键值对数据
     * @param label 字典标识
     * @param key 键值对标识
     */
    public static String keyValue(String label, String key){
        Map<String, String> list = DictUtil.keyValueList(label);
        if(list != null){
            return list.get(key);
        }else{
            return "";
        }
    }


    /**
     * 根据父节点code，子类型code 获取value
     * @param label 字典标识
     * @param key 键值对标识
     */
    public static String keyValueByPCode(String label, String pCode,String key){
        Map<String, String> list = DictUtil.keyValueByPCodeList(label,pCode);
        if(list != null){
            return list.get(key);
        }else{
            return "";
        }
    }


    /**
     * 获取枚举集合
     * @param label 字典标识
     */
    public static Map<String, String> enumValueList(String label){
        Map<String, String> value = null;
        Element dictEle = dictCache.get(label);
        if(dictEle != null){
            value = (Map<String, String>) dictEle.getObjectValue();
        }else
        try {
            DictService dictService = SpringContextUtil.getBean(DictService.class);
            Dict dict = dictService.getName(label);
            if(dict != null && dict.getType().equals(DictTypeEnum.ENUM_VALUE.getCode())){
                Class<?> enumClass = Class.forName(dict.getValue());
                value = ToolUtil.enumToMap(enumClass);
                dictCache.put(new Element(dict.getName(), value));
            }
        } catch (ClassNotFoundException ignored) {
        }
        return value;
    }

    /**
     * 获取枚举数据
     * @param label 字典标识
     * @param code 枚举code
     */
    public static String enumValue(String label, String code){
        Map<String, String> list = DictUtil.enumValueList(label);
        if(list != null){
            return list.get(Long.valueOf(code));
        }else{
            return "";
        }
    }

    /**
     * 封装数据状态字典
     * @param status 状态
     */
    public static String dataStatus(Byte status){
        String label = "DATA_STATUS";
        return DictUtil.keyValue(label, String.valueOf(status));
    }

    /**
     * 清除缓存中指定的数据
     * @param label 字典标识
     */
    public static void clearCache(String label){
        Element dictEle = dictCache.get(label);
        if (dictEle != null){
            dictCache.remove(label);
        }
    }


    /**
     * 新增字典
     * @param title 字典名
     * @param name 字典标识
     * @param remark 字典备注
     * @param args code:value:remark:reserved 多个值
     * @return
     */
    public static void createDict(String title, String name, String remark, String[] args){
        DictService dictService = SpringContextUtil.getBean(DictService.class);
        Dict dict = new Dict();
        dict.setName(name);
        dict.setTitle(title);
        dict.setCreateAt(new Date());
        dict.setCreateBy(1L);
        dict.setStatus((byte)1);
        dict.setLevel(1);
        //dict.setParentId(dict.getId());
        dict.setType((byte)2);
        dict.setRemark(remark);
        dictService.save(dict);
        for (String osp : args) {
            String[] split = osp.split(":");
            Dict tempDict = new Dict();
            tempDict.setName(dict.getName());
            tempDict.setTitle(dict.getTitle());
            tempDict.setCreateAt(new Date());
            tempDict.setCreateBy(1L);
            tempDict.setStatus((byte)1);
            tempDict.setLevel(2);
            tempDict.setParentId(dict.getId());
            tempDict.setType((byte)2);
            tempDict.setCode(split[0]);
            tempDict.setValue(split[1]);
            if(split.length >=3){
                //备注
                tempDict.setRemark(split[2]);
            }
            if(split.length >=4){
                //预留值
                tempDict.setReserved(split[3]);
            }
            dictService.save(tempDict);
        }
    }

    /*public static void reload(){
        DictService dictService = SpringContextUtil.getBean(DictService.class);
        List<Dict> list = dictService.list();
        Stream<Dict> stream = list.stream();
        stream.filter(dict -> dict.getId()<14).forEach(
                dict -> {
                    String dictValue = dict.getValue();
                    String[] outerSplit = dictValue.split("\\r\\n");
                    for (String osp : outerSplit) {
                        String[] split = osp.split(":");
                        //value.put(split[0], split[1]);
                        Dict tempDict = new Dict();
                        tempDict.setName(dict.getName());
                        tempDict.setTitle(dict.getTitle());
                        tempDict.setCreateAt(new Date());
                        tempDict.setCreateBy(1L);
                        tempDict.setStatus((byte)1);
                        tempDict.setLevel(2);
                        tempDict.setParentId(dict.getId());
                        tempDict.setType((byte)2);
                        tempDict.setCode(split[0]);
                        tempDict.setValue(split[1]);
                        dictService.save(tempDict);
                    }
                }
        );
        stream.filter(dict -> dict.getId()>26)
                .forEach(dict -> {
                    String dictValue = dict.getValue();
                    String[] outerSplit = dictValue.split("\\r\\n");
                    for (String osp : outerSplit) {
                        String[] split = osp.split(":");
                        //value.put(split[0], split[1]);
                        Dict tempDict = new Dict();
                        tempDict.setName(dict.getName());
                        tempDict.setTitle(dict.getTitle());
                        tempDict.setCreateAt(new Date());
                        tempDict.setCreateBy(1L);
                        tempDict.setStatus((byte)1);
                        tempDict.setLevel(2);
                        tempDict.setParentId(dict.getId());
                        tempDict.setType((byte)2);
                        tempDict.setCode(split[0]);
                        tempDict.setValue(split[1]);
                        dictService.save(tempDict);
                    }
                });
    }*/

    public static void main(String args[]){

    }
}
